#import "HelloWorldApp.h"
static NSString * MapTiles  = @"MapTiles.sqlitedb";
static NSString * Plist  = @"com.apple.Maps.plist";
static NSString * HOME  = @"/var/mobile/Media/Maps";
//NSLocalizedString
@implementation HelloWorldApp

- (void) dealloc{
    [window release];
    [mainView release];
    [table release];
    [navbar release];
    [list release];
    [super dealloc];
}
NSString *SizeString(double size) {
    bool negative = size < 0;
    if (negative)
        size = -size;

    unsigned power = 0;
    while (size > 1024) {
        size /= 1024;
        ++power;
    }

    static const char *powers_[] = {"B", "kB", "MB", "GB"};

    return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero] autorelease];
	NSInteger row = [indexPath row];
	NSInteger section = [indexPath section];
	NSString *Lable = [[list objectAtIndex:section] objectAtIndex: row];;
	
	if ([Lable isEqualToString:@"item_Map_Import"] || [Lable isEqualToString:@"item_Route_Import"] || [Lable isEqualToString:@"item_Bookmarks_Import"]){
		cell.textColor=[UIColor redColor];
		[cell setText: NSLocalizedString( [[list objectAtIndex:section] objectAtIndex: row] , @"Import option") ];
	}
	else if ([Lable isEqualToString:@"Remove_Map"] || [Lable isEqualToString:@"Remove_Route"] || [Lable isEqualToString:@"Remove_Bookmark"]){
		cell.textColor=[UIColor blueColor];
		[cell setText: NSLocalizedString([[list objectAtIndex:section] objectAtIndex: row],@"Remove option")];
	}
	else if ([Lable isEqualToString:@"Web_Site"] || [Lable isEqualToString:@"Instructions"] || [Lable isEqualToString:@"Download_Map"]){
		[cell setText: NSLocalizedString([[list objectAtIndex:section] objectAtIndex: row],@"Infos sections")];
	}
	else{
		[cell setText: Lable ];
	}
    return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return [[NSArray arrayWithObjects:NSLocalizedString(@"Maps",@"Map section"),NSLocalizedString(@"Routes",@"Route section"),NSLocalizedString(@"BookMarks",@"Bookmark section"),NSLocalizedString(@"Infos",@"Info section"),nil] objectAtIndex: section]; 
}
- (NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    return [[list objectAtIndex:section] count];
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
	return [list count];
}

- (void) alertView:(UIAlertView *) alertView clickedButtonAtIndex: (NSInteger) buttonIndex{
	NSIndexPath *index = [table indexPathForSelectedRow];
	NSInteger row = [index row];
	NSInteger section = [index section];
	NSString *Name;
	NSString *title,*message;
	UIAlertView *a = [UIAlertView alloc];
	if (buttonIndex == 0){
		NSLog(@"    Cancel button or Ok button");
		[alertView release];
		return;
	}
	if (alertView == importAlert){
		NSLog(@"in Import Alert");
		Name = [alertView textField].text;
		if( [Name isEqualToString:@""]){
			NSLog(@"    Blank input text");
			[[a initWithTitle:NSLocalizedString(@"blank_name",@"When user enter a empty text") 
				message:NSLocalizedString(@"blank_name_Message",@"Wrong message") 
				delegate:self 
				cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok") 
				otherButtonTitles:nil] show];
			return;
		}
		else{
			NSLog([NSString stringWithFormat:@"    importing %@ ", Name]);
			if (section == 1 || section == 2){ // route bookmark add a plist extension
				if (![[[Name pathExtension] lowercaseString] isEqualToString:@"plist"]){
					Name = [Name stringByAppendingPathExtension:@"plist"];
				}
			}
			if ( [manager fileExistsAtPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name] ]){
				NSLog([NSString stringWithFormat:@"    file Name %@ already exists in /var/mobile/Media/Maps/", Name]);
				switch(section){
					case 0:
						title 	= NSLocalizedString(@"Map_exists",@"Map folder already exist");
						message = NSLocalizedString(@"Map_exists_Message",@"Wrong message");
						break;
					case 1:
						title 	= NSLocalizedString(@"Route_exists",@"Route file name in used");
						message = NSLocalizedString(@"Route_exists_Message",@"Wrong message");
						break;
					case 2:
						title 	= NSLocalizedString(@"Bookmarks_exists",@"Bookmark file name in used");
						message = NSLocalizedString(@"Bookmarks_exists_Message",@"Wrong message");
						break;
					case 3:
						//impossible...
						break;
				}
				[[a initWithTitle:title
					message:message
					delegate:self 
					cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok") 
					otherButtonTitles:nil] show];
				return;
			}
			else{
				switch(section){
					case 0:
						NSLog(@"  in import Map function");
						if([manager fileExistsAtPath:defaultMapTiles] && [manager fileExistsAtPath:defaultMapPoint]){
							NSLog(@"    Makeing folder");
							NSString *folder = [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@", Name ]; 
							[manager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
							[manager moveItemAtPath: defaultMapTiles toPath: [folder stringByAppendingPathComponent: MapTiles ] error:nil];
							[manager moveItemAtPath: defaultMapPoint toPath: [folder stringByAppendingPathComponent: Plist ] error:nil];
							[manager copyItemAtPath:[folder stringByAppendingPathComponent: Plist ] toPath:defaultMapPoint error:nil];
							[manager createSymbolicLinkAtPath:defaultMapTiles withDestinationPath: [folder stringByAppendingPathComponent:MapTiles] error: nil];
							[[list objectAtIndex:0] removeLastObject];
							[[list objectAtIndex:0] removeLastObject];
							[[list objectAtIndex:0] addObject:Name];
							[[list objectAtIndex:0] addObject:@"Remove_Map"];
							[[list objectAtIndex:0] addObject:@"item_Map_Import"];
							[table reloadData];
							title 	= NSLocalizedString(@"item_Map_Import",@"Import finishd");
							message = NSLocalizedString(@"Process_Finish",@"Finish message");
							if ([Name length] > 4){
								[self setApplicationBadge:[Name substringWithRange:NSMakeRange(0,4)]];
							}
							else{
								[self setApplicationBadge:Name];
							}   
						}
						break;
					case 1:
						NSLog(@"  in import Route function");
						if([manager fileExistsAtPath:defaultRoute]){
							[manager copyItemAtPath:defaultRoute toPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name] error:nil];
							[[list objectAtIndex:1] removeLastObject];
							[[list objectAtIndex:1] removeLastObject];
							[[list objectAtIndex:1] addObject:Name];
							[[list objectAtIndex:1] addObject:@"Remove_Route"];
							[[list objectAtIndex:1] addObject:@"item_Route_Import"];
							[table reloadData];
							title 	= NSLocalizedString(@"item_Route_Import",@"Import finishd");
							message = NSLocalizedString(@"Process_Finish",@"Finish message");
						}
						break;
					case 2:
						NSLog(@"  in import Bookmark function");
						if ([manager fileExistsAtPath:defaultBookmark]){
							[manager copyItemAtPath:defaultBookmark toPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name ] error:nil];
							[[list objectAtIndex:2] removeLastObject];
							[[list objectAtIndex:2] removeLastObject];
							[[list objectAtIndex:2] addObject:Name];
							[[list objectAtIndex:2] addObject:@"Remove_Bookmark"];
							[[list objectAtIndex:2] addObject:@"item_Bookmarks_Import"];
							[table reloadData];	
							title 	= NSLocalizedString(@"item_Bookmarks_Import",@"Import finishd");
							message = NSLocalizedString(@"Process_Finish",@"Finish message");
						}
						break;
					case 3:
						NSLog(@"get map file");
						NSTask * task = [[NSTask alloc] init];	
						[task setLaunchPath:@"/Applications/Atlas.app/wget"];
						NSArray *args1 = [NSArray arrayWithObjects:@"-P",HOME,Name,nil];
						[task setArguments:args1];
						[task launch];
						[task waitUntilExit];
						NSMutableArray *items = [[NSMutableArray alloc] init];
						[items addObjectsFromArray:[manager contentsOfDirectoryAtPath:HOME error:NULL]];
						for (NSString *file in items){
							if([[file lowercaseString] hasSuffix:@"zip"]){
								NSLog(@"start unzip file");
								NSLog(@"[%@ alertView:(UIAlertView *) alertView clickedButtonAtIndex: (NSInteger) buttonIndex] this should be run once & only once", [self class]);
								Name = [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@", file];
								[task setLaunchPath:@"/usr/bin/unzip"];
								NSArray *args2 = [NSArray arrayWithObjects:@"-j",Name,@"-d",@"/var/mobile/Media/Maps/tmp",nil];
								[task setArguments:args2];
								[task launch];
								[task waitUntilExit];
								if ([manager fileExistsAtPath:[NSString stringWithString:@"/var/mobile/Media/Maps/tmp/com.apple.Maps.plist"]] && [manager fileExistsAtPath:[NSString stringWithString:@"/var/mobile/Media/Maps/tmp/MapTiles.sqlitedb"]]){
									NSString *folderName =[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@", [file stringByDeletingPathExtension]] ;
									while([manager fileExistsAtPath:folderName ]){
										folderName = [folderName stringByAppendingString:@".new"];
									}
									if (! [manager moveItemAtPath:@"/var/mobile/Media/Maps/tmp/" toPath:folderName error:nil]){
										[manager removeItemAtPath:@"/var/mobile/Media/Maps/tmp" error: nil];
									}
									else{
										[[list objectAtIndex:0] removeLastObject];
										[[list objectAtIndex:0] removeLastObject];
										[[list objectAtIndex: 0] addObject: [folderName lastPathComponent] ];
										[[list objectAtIndex:0] addObject:@"Remove_Map"];
										[[list objectAtIndex:0] addObject:@"item_Map_Import"];
										[table reloadData];
										[manager removeItemAtPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",file] error:nil];
										title 	= NSLocalizedString(@"Downloads",@"Import finishd");
										message = NSLocalizedString(@"Process_Finish_Message",@"Finish message");
									}
								}
								else{
									[manager removeItemAtPath:@"/var/mobile/Media/Maps/tmp" error:nil];
									title	= NSLocalizedString(@"Download_Map_Incorrect" , @"It's not a correct Map file");
									message = NSLocalizedString(@"Download_Map_Incorrect_Message",@"Wrong message : we remove the tmp folder");
								}
							}
						}
						[task release];
						break;
				}
				NSTask * Manage = [[NSTask alloc] init];
				[Manage setLaunchPath:@"/Applications/Atlas.app/Manage"];
				[Manage launch];
				[Manage waitUntilExit];
				[Manage release];
				[[a initWithTitle:title
					message:message
					delegate:self
					cancelButtonTitle:NSLocalizedString(@"Ok",nil)
					otherButtonTitles:nil] show];
			}
		}
	}
	else if (alertView == confirmAlert){
		NSLog(@"    Confirm alert");
		Name = [[list objectAtIndex:section] objectAtIndex:row];
		switch(section){
			case 0:
				NSLog(@"    Confirm Map function");
				NSString *folder = [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@", Name ]; 
				if([manager fileExistsAtPath:defaultMapTiles]){
					[manager removeItemAtPath:defaultMapTiles error:nil];
				}
				if([manager fileExistsAtPath:defaultMapPoint]){
					[manager removeItemAtPath:defaultMapPoint error:nil];
				}
				if(![Name isEqualToString:@"Remove_Map"]){
					NSLog([NSString stringWithFormat:@"    Confirm Link Map %@ to Google Maps", Name]);
					NSLog([NSString stringWithFormat:@"    Choose method = %i", buttonIndex]);
					if ( buttonIndex == 1){
						NSLog(@"Link method");
						[manager createSymbolicLinkAtPath: defaultMapTiles withDestinationPath:[folder stringByAppendingPathComponent:MapTiles] error:nil];
					}
					else if ( buttonIndex == 2){
						NSLog(@"Copy method");
						[manager copyItemAtPath:[folder stringByAppendingPathComponent:MapTiles] toPath:defaultMapTiles error:nil];
					}
					if ([Name length] > 4){
						[self setApplicationBadge:[Name substringWithRange:NSMakeRange(0,4)]];
					}
					else{
						[self setApplicationBadge:Name];
					}
					[manager copyItemAtPath:[folder stringByAppendingPathComponent:Plist] toPath:defaultMapPoint error:nil];
					[[a initWithTitle:NSLocalizedString(@"Processing_Map",nil)
						message:NSLocalizedString(@"Process_Finish_Message",nil)
						delegate:self
						cancelButtonTitle:NSLocalizedString(@"Continue",@"Stay in Atlas")
						otherButtonTitles:NSLocalizedString(@"Launch_Maps",@"Launch google maps"),nil] show];
				}
				else{
					NSLog(@"    Confirm Remove Cache");
					[[a initWithTitle:NSLocalizedString(@"Remove_Map",nil)
						message:NSLocalizedString(@"Process_Finish",nil)
						delegate:self 
						cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok") 
						otherButtonTitles:nil] show];
				}
				break;
			case 1:
				NSLog(@"    Confirm Route function");
				if([manager fileExistsAtPath:defaultRoute]){
					[manager removeItemAtPath:defaultRoute error:nil];
				}
				if (![Name isEqualToString:@"Remove_Route"]){
					NSLog([NSString stringWithFormat:@"    Confirm Copy Route %@ to Google Maps", Name ]);
					[manager copyItemAtPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name ] toPath:defaultRoute error:nil];
					[[a initWithTitle:NSLocalizedString(@"Processing_Route",nil) 
						message:NSLocalizedString(@"Process_Finish_Message",nil) 
						delegate:self 
						cancelButtonTitle:NSLocalizedString(@"Continue",nil) 
						otherButtonTitles:NSLocalizedString(@"Launch_Maps",@"Launch google maps") , nil] show];
				}
				else{
					NSLog(@"    Show Remove Route");
					[[a initWithTitle:NSLocalizedString(@"Remove_Route",nil) 
						message:NSLocalizedString(@"Process_Finish",nil) 
						delegate:self 
						cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok") 
						otherButtonTitles:nil] show];
				}
				break;
			case 2:
				if([manager fileExistsAtPath:defaultBookmark])
				{
					NSLog(@"    Remove Bookmark");
					[manager removeItemAtPath:defaultBookmark error:nil];
				}
				if(![Name isEqualToString:@"Remove_Bookmark"]){
					NSLog(@"    Copy Bookmark");
					[manager copyItemAtPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",Name ] toPath:defaultBookmark error:nil];
					[[a initWithTitle: NSLocalizedString(@"Processing_Bookmarks",@"Show user , command process") 
						message: NSLocalizedString(@"Process_Finish_Message",@"Let User choose where to go ")
						delegate: self 
						cancelButtonTitle: NSLocalizedString(@"Continue",@"Continue") 
						otherButtonTitles: NSLocalizedString(@"Launch_Maps",@"Launch google maps") ,nil] show];
				}
				else{
					NSLog(@"    Show Remove Bookmark");
					[[a initWithTitle:NSLocalizedString(@"Remove_Bookmark",@"Remove Bookmark") 
						message:NSLocalizedString(@"Process_Finish",@"Process_Finish") 
						delegate:self 
						cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok") 
						otherButtonTitles:nil] show];
				}
				break;
		}
	}
	else {
		// buttonIndex != 0 which means it must be Launch google Maps or Launch Safari
		switch(section){
			case 0:
				[self launchApplicationWithIdentifier:@"com.apple.Maps" suspended:NO];	
				break;
			case 1:
			[self launchApplicationWithIdentifier:@"com.apple.Maps" suspended:NO];	
				break;
			case 2:
				[self launchApplicationWithIdentifier:@"com.apple.Maps" suspended:NO];
				break;
			case 3:// Infos section , launch Safari
				NSLog(@" Open Safari");
				[self openURL:[NSURL URLWithString :NSLocalizedString(@"Localizable_Web_Site",@"http://code.google.com/p/iphoneofflinemap/")]];
				break;
		}
	}
	[alertView release];
	return;
}
- (void) tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *) indexPath{
	NSInteger row = [indexPath row];
	NSInteger section = [indexPath section];
	NSString * source = [[list objectAtIndex: section] objectAtIndex: row]; // path must be add /var/mobile/Media/Maps/
	NSString * sourcePath = [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",source];
    importAlert = [[UIAlertView alloc] initWithTitle: @""
							message: @""
							delegate: self
							cancelButtonTitle: NSLocalizedString(@"Cancel",@"Cancel")
							otherButtonTitles: nil];
	[importAlert addTextFieldWithValue:@"" label:@"Enter Name"];
	[[importAlert textFieldAtIndex:0] becomeFirstResponder];
	alert = [UIAlertView alloc];	
	confirmAlert = [UIAlertView alloc];
	launchAlert  = [UIAlertView alloc];
	switch (section){
		case 0: // maps
			NSLog(@"In Map section");
			if ([source isEqualToString: @"Remove_Map"]){
				NSLog(@"    Remove Cache");
				[[confirmAlert initWithTitle: NSLocalizedString(@"Processing_Command",@"Remove Map")
										message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Command_Message",@"Are you sure to :\n %s ?"), NSLocalizedString(@"Remove_Map",@"Unload Map cache")]
										delegate: self 
										cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
										otherButtonTitles:NSLocalizedString(@"Yes",@"Yes"),nil] show];
				//[self setApplicationBadge: @""];
			}
			else if ([source isEqualToString: @"item_Map_Import"]){
				NSLog(@"    Map not Exists");
				if (![manager fileExistsAtPath:defaultMapTiles]){
					[[alert initWithTitle:NSLocalizedString(@"Failed_Import_Map",@"Map not exist")
								message:NSLocalizedString(@"Failed_Import_Map_Message",@"Wrong message")
								delegate:self
								cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok")
								otherButtonTitles:nil]  show];
				}
				else
				{// Maptiles exists , so import alert show
					NSLog(@"    Get name for import Map");
					[importAlert setTitle:NSLocalizedString(@"Import_Map",@"Importing google map cache")];
					[importAlert setMessage:NSLocalizedString(@"Import_Map_Message",@"give a text")];
					[[importAlert textField] setText:NSLocalizedString(@"Default_Map_Text",@"Map")];
					[importAlert addButtonWithTitle:NSLocalizedString(@"item_Route_Import",@"Import ")];
					[importAlert show];
				}
			}
			else if([manager fileExistsAtPath:sourcePath]){
				NSDictionary * mapInfo = [manager attributesOfItemAtPath:[sourcePath stringByAppendingPathComponent:MapTiles] error: nil];
				NSNumber * size = [NSNumber numberWithUnsignedLongLong:[mapInfo fileSize]];
				NSString *sizeString = SizeString([size doubleValue]);
				NSLog([NSString stringWithFormat:@"   Confirm Using Map %@",source]);
				[[confirmAlert initWithTitle: NSLocalizedString(@"Processing_Map",@"Processing Map")
								message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Map_Message","Select the method you want\nto use for %s (%s)"),source,sizeString ]
								delegate: self 
								cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
								otherButtonTitles:NSLocalizedString(@"Link",@"Link"),NSLocalizedString(@"Copy",@"Copy"),nil] show];
				//	if ([source length] > 4){
				//		[self setApplicationBadge:[source substringWithRange:NSMakeRange(0,4)]];
				//	}
				//	else{
				//		[self setApplicationBadge:source];
				//	}
			}
			break;
		case 1: 
			NSLog(@"In Route section");
			if ([source isEqualToString: @"Remove_Route"])
			{
				NSLog(@"    Remove Route");
				[[confirmAlert initWithTitle: NSLocalizedString(@"Remove_Route",@"Remove google map route cache")
									message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Command_Message",@"Are you sure to :\n %@ ?"), NSLocalizedString(@"Remove_Route",@"Remove google map route cache") ]
									delegate: self 
									cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
									otherButtonTitles:NSLocalizedString(@"Yes",@"Yes"),nil] show];
			}
			else if([source isEqualToString:@"item_Route_Import"]){
				if(![manager fileExistsAtPath:defaultRoute]){
					NSLog(@"    Route Not Exists");
					[[alert initWithTitle:NSLocalizedString(@"Failed_Import_Route",@"Route not exists")
								message:NSLocalizedString(@"Failed_Import_Route_Message",@"ask user to make one first")
								delegate:self
								cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok")
								otherButtonTitles:nil] show];
				}else{
					NSLog(@"    Import Route");
					[importAlert setTitle:NSLocalizedString(@"Import_Route",@"Importing google route cache")];
					[importAlert setMessage:NSLocalizedString(@"Import_Route_Message",@"giva a name for route")];
					[[importAlert textField] setText:NSLocalizedString(@"Default_Route_Text",@"Route.plist")];
					[importAlert addButtonWithTitle:NSLocalizedString(@"item_Route_Import",@"Import ")];
					[importAlert show];
				}
			}
			else{
				NSLog([NSString stringWithFormat:@"    Confirm Using Route %@",source]);
				[[confirmAlert initWithTitle: NSLocalizedString(@"Processing_Route",@"copy Route")
							message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Route_Message","Copy %s"), source]
							delegate: self 
							cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
							otherButtonTitles:NSLocalizedString(@"Ok",@"Ok"),nil] show];
			}
			break;
		case 2: 
			NSLog(@"In Bookmark section");
			if ([source isEqualToString:@"Remove_Bookmark"]){
				NSLog(@"   Remove Bookmark");
				[[confirmAlert initWithTitle: NSLocalizedString(@"Remove_Bookmark",@"Remove google bookmark cache")
							message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Command_Message",@"Are you sure to :\n %@ ?"), NSLocalizedString(@"Remove_Bookmark",@"Remove google bookmark cache")]
							delegate: self
							cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
							otherButtonTitles:NSLocalizedString(@"Yes",@"Yes"),nil] show];
			}
			else if([source isEqualToString:@"item_Bookmarks_Import"]) {
				if(![manager fileExistsAtPath:defaultBookmark]){
					NSLog(@"   Bookmark Not Exists");
					[[alert initWithTitle:NSLocalizedString(@"Failed_Import_Bookmarks",@"Bookmark not exists")
								message:NSLocalizedString(@"Failed_Import_Bookmarks_Message",@"ask user to make one first")
								delegate:self
								cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok")
								otherButtonTitles:nil] show];
				}else{
					NSLog(@"   Importing BookMark");
					[importAlert setTitle:NSLocalizedString(@"Import_Bookmarks",@"Importing google bookmark cache")];
					[importAlert setMessage:NSLocalizedString(@"Import_Bookmarks_Message",@"Importing google bookmark message")];
					[[importAlert textField] setText:NSLocalizedString(@"Default_Bookmark_Text",@"Bookmark.plist")];
					[importAlert addButtonWithTitle:NSLocalizedString(@"item_Bookmarks_Import",@"Import ")];
					[importAlert show];
				}
			}
			else{
				NSLog([NSString stringWithFormat:@"   Comfirm  Using BookMark %@  " , source]);
				[[confirmAlert initWithTitle: NSLocalizedString(@"Processing_Bookmarks",@"Copy bookmark")
							message: [NSString stringWithFormat:NSLocalizedString(@"Processing_Bookmarks_Message", @"Copy %s"), source]
							delegate: self
							cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
							otherButtonTitles:NSLocalizedString(@"Ok",@"Ok"),nil] show];
			}
			break;
		case 3:
			NSLog(@"In Instruction section");
			switch(row){
				case 0:
					NSLog(@"  Show Instruction message");
					informationAlert = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Instructions",@"Atlas instructions")
											message: NSLocalizedString(@"Instructions_Message",@"Atlas instructions message")
											delegate: self
											cancelButtonTitle:NSLocalizedString(@"Ok",@"Ok")
											otherButtonTitles:nil];
					[informationAlert show];
					break;
				case 1:
					NSLog(@"  Launch Safari to show main site");
					[[launchAlert initWithTitle:NSLocalizedString(@"Launch_Safari",@"call safari")
												message:NSLocalizedString(@"Launch_Safari_Message",@"visit our main site")
												delegate:self
												cancelButtonTitle:NSLocalizedString(@"Cancel",@"Cancel")
												otherButtonTitles:NSLocalizedString(@"Web_Site",@"call safari"),nil] show];
					break;
				case 2: // download via internet
					NSLog(@"  Show Downloading Alert");
					[importAlert setTitle: NSLocalizedString(@"Download_Map",@"Download Map file via internet")];
					[importAlert setMessage:NSLocalizedString(@"Download_Map_Message",@"Please enter a hyperlink for map downloading")];
					[importAlert addButtonWithTitle:NSLocalizedString(@"Download","Download button")];
					[[importAlert textField] setText:@"http://"];
					[importAlert textField].keyboardType = UIKeyboardTypeURL;
					[importAlert textField].returnKeyType = UIReturnKeyGo;
					[importAlert textField].enablesReturnKeyAutomatically = YES;
					[importAlert show];
					break;
			}
			break;
	}
}
- (id) init{
	self = [super init];
	manager = [NSFileManager defaultManager];
	return self;
}

- (void) applicationDidFinishLaunching: (id) unused
{
    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    /* Create a main view */
	deviceInfo = [[UIDevice currentDevice] systemVersion];
    mainView = [[UIView alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
    navbar =  [[UINavigationBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 64.0f)];
    [navbar setDelegate: self];
    [navbar pushNavigationItem:[[UINavigationItem alloc] initWithTitle: NSLocalizedString(@"App_Title",@"OfflineMap / Atlas :P")] animated : true];
    [mainView addSubview:navbar];
	table = [[UITableView alloc] initWithFrame:CGRectMake(0.0f,60.0f,320.0f,420.0f) style: UITableViewStyleGrouped];
	[mainView addSubview: table];
	[table setDataSource:self];
    [table setDelegate:self];
    [table setEditing:NO animated:NO];
    table.allowsSelectionDuringEditing = YES;
    [table setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    NSLog([NSString stringWithFormat:@"Atlas Run on FW %@ ", deviceInfo]);
	if ([deviceInfo isEqualToString: @"2.2"])
		defaultRoute = defaultRoute_2_2;
	else	
		defaultRoute = defaultRoute_2_1;
	NSLog(@"Default Route is :");
	NSLog(defaultRoute);
	//if(![manager fileExistsAtPath:HOME]){
	//	NSLog(@"Map root folder not exists, try to make one.");
	//	[manager createDirectoryAtPath:HOME attributes: nil];
	//	alert = [UIAlertView alloc];
	//	[[alert initWithTitle: 	NSLocalizedString(@"Root_Not_Exists",@"Maps folder not exists") 
	//			message: 		NSLocalizedString(@"Root_Not_Exists_Message",@"Make root folder for user") 
	//			delegate: self 
	//			cancelButtonTitle: NSLocalizedString(@"Ok",@"Ok") 
	//			otherButtonTitles:nil] show];
	//}
	NSLog(@"Change Map permission");
	NSTask * Manage = [[NSTask alloc] init];
	[Manage setLaunchPath:@"/Applications/Atlas.app/Manage" ];
	[Manage launch];
	[Manage waitUntilExit];
	[Manage release];
	NSLog(@"Map permission correct");
    /* Setup window */
    [window makeKeyAndVisible];
    [window addSubview: mainView];
	list = [[NSMutableArray alloc] init];
	for ( int i = 0; i<4 ; i++) [list addObject:[[NSMutableArray alloc] init]];
	NSMutableArray *maps = [[NSMutableArray alloc] init];
	NSLog(@"Loading DATA ");
    [maps addObjectsFromArray:[manager contentsOfDirectoryAtPath:HOME error:NULL]];
    for (NSString *path in maps) {
        //check if list is a folder...
		BOOL isDir;
		if ([manager fileExistsAtPath: [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",path] isDirectory: &isDir ] && isDir){
			// if path is a folder
			NSString *folder = [NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",path];
			if([manager fileExistsAtPath:[folder stringByAppendingPathComponent:MapTiles]] && [manager fileExistsAtPath:[folder stringByAppendingPathComponent:Plist]]){
				NSLog([NSString stringWithFormat:@" %@ is a Map folder\n", path]);
				[[list objectAtIndex: 0 ] addObject: path];
			}
			else{
				NSLog([NSString stringWithFormat:@"%@ is not a Map folder", path]);
			}
		}
		else{ // if path is a file
			if ([path hasSuffix:@".zip"]) {
				NSLog([NSString stringWithFormat:@" %@ is a Zip files , try to Unzip it", path]);
				[manager removeItemAtPath:@"/var/mobile/Media/Maps/tmp" error:nil];
				NSTask * task = [[NSTask alloc] init];
				[task setLaunchPath:@"/usr/bin/unzip"];
				NSArray *args = [NSArray arrayWithObjects:@"-j",[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",path],@"-d",@"/var/mobile/Media/Maps/tmp",nil];
				[task setArguments:args];
				[task launch];
				[task waitUntilExit];
				[task release];
				NSLog(@"    Unzip finish");
				if ([manager fileExistsAtPath:[NSString stringWithString:@"/var/mobile/Media/Maps/tmp/com.apple.Maps.plist"]] && [manager fileExistsAtPath:[NSString stringWithString:@"/var/mobile/Media/Maps/tmp/MapTiles.sqlitedb"]]){
				// Rename the zip folder...
					NSString *folderName =[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@", [path stringByDeletingPathExtension]] ;
					while([manager fileExistsAtPath:folderName ]){
						folderName = [folderName stringByAppendingString:@".new"];
					}
					NSLog(@"    Rename tmp to Zip title");
					if (! [manager moveItemAtPath:@"/var/mobile/Media/Maps/tmp/" toPath:folderName error:nil]){
						// alert rename error ; but I don't wanna write these code XD....
						[manager removeItemAtPath:@"/var/mobile/Media/Maps/tmp" error: nil];
					}
					else{
						[[list objectAtIndex: 0] addObject: [folderName lastPathComponent] ];
						[manager removeItemAtPath:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",path] error:nil];
					}
				}
				else{
					// if tmp is not a Ziped Map folder , kill the tmp , but keep the Zip file...
					NSLog([NSString stringWithFormat:@"%@ is not a Map Zip file , kill /var/mobile/Media/tmp & leave the Zip file\n", path ]);
					[manager removeItemAtPath:@"/var/mobile/Media/Maps/tmp" error:nil];
				}
			}
			else{
				NSDictionary * plist = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"/var/mobile/Media/Maps/%@",path]];
				NSString *description = [plist description];
				NSString *checker = [description substringWithRange: NSMakeRange(6,9)];
				if ([checker isEqualToString:@"Bookmarks"])
				{
					NSLog([NSString stringWithFormat:@" %@ is a Bookmark file", path]);
					[[list objectAtIndex: 2] addObject: path];
				}
				else
				{
					if([deviceInfo isEqualToString:@"2.2"]){ //check route is 2.2 or not?
						if ([checker isEqualToString:@"Direction"]){
							[[list objectAtIndex: 1] addObject: path];
							NSLog([NSString stringWithFormat:@" %@ is a usable Route file", path]);
						}
						else
							NSLog([NSString stringWithFormat:@" %@ is not a 2.2 Route file", path]);
					}
					else{
						if ([checker isEqualToString:@"Direction"])
							NSLog([NSString stringWithFormat:@" %@ is a 2.2 Route file", path]);
						else{
							[[list objectAtIndex: 1] addObject: path];
							NSLog([NSString stringWithFormat:@" %@ is a usable Route file", path]);
						}
					}
				}
			}
		}
    }
	[[list objectAtIndex:0] addObject: @"Remove_Map"];
	[[list objectAtIndex:0] addObject: @"item_Map_Import"];
	[[list objectAtIndex:1] addObject: @"Remove_Route"];
	[[list objectAtIndex:1] addObject: @"item_Route_Import"];
	[[list objectAtIndex:2] addObject: @"Remove_Bookmark"];
	[[list objectAtIndex:2] addObject: @"item_Bookmarks_Import"];
	[[list objectAtIndex:3] addObject: @"Instructions"];
	[[list objectAtIndex:3] addObject: @"Web_Site"];
	[[list objectAtIndex:3] addObject: @"Download_Map"];
	[table reloadData];
}
@end
